import axios from 'axios';
import { notification } from "ant-design-vue";
import store from '@/store'; // 示例：从Vuex中获取store对象，用于处理token等问题
import router from '@/router';

// 创建axios实例并配置基础URL和默认请求头
const instance = axios.create({
    baseURL: process.env.VUE_APP_SERVER || 'http://localhost:8000/', // 使用环境变量
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    },
});

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        // 在发送请求之前做些什么
        // 如添加Authorization token到headers
        const token = store.state.member.token;
        if (token) {
            config.headers.token = token;
        }
        return config;
    },
    (error) => {
        console.error('Request Error:', error);
        Promise.reject(error);
    },
);

// 响应拦截器
instance.interceptors.response.use(
    (response) => {
        // 处理成功的HTTP响应
        if (!response.data.success) {
            notification.error({ description: response.data.message || '请求失败' });
        }
        return Promise.resolve(response.data);
    },
    (error) => {
        if (error.response) {
            // 处理错误的HTTP响应
            if (error.response.status === 401) {
                // 示例：当收到401未授权错误时，清除token并跳转登录页面
                store.commit("setMember", {});
                notification.error({ description: "未登录或登陆超时" });
                router.push("/login");
                return Promise.reject(error);
            }
            const errorMessage = error.response?.data?.message || '网络异常，请稍后再试';
            notification.error({ description: errorMessage });
            return Promise.reject(error);
        }
    },
);

export default instance;

// 示例：封装GET和POST方法
export const get = (url, params) => instance.get(url, { params });
export const post = (url, data) => instance.post(url, data);
export const del = (url) => instance.delete(url);